﻿using BaseUi.Db.Models;
using LiveCharts;
using MySqlConnector;
using Ping9719.DeviceCommunication;
using Ping9719.WpfEx;
using Ping9719.WpfEx.Mvvm;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using static BaseUi.Db.Models.MESModels;

namespace BaseUi.ViewModel
{
    public class HomeViewModel : BindableBase
    {
        public WrapPanel panel { get; set; }

        List<ChannelViewModel> panelviewModels = new List<ChannelViewModel>();

        List<HTZD_Assemble> HTZD_Assemble1 = new List<HTZD_Assemble>();
        List<HTZD_Assemble> HTZD_Assemble2 = new List<HTZD_Assemble>();

        CancellationTokenSource cancellationToken = null;//停止
        ManualResetEvent manualReset = null;//暂停、继续
        WarnInfoContainer WarnInfo = new WarnInfoContainer();//警告、错误等信息

        private string code1_ ;
        public string code1 { get => code1_; set { SetProperty(ref code1_, value); } }
        private string code2_ ;
        public string code2 { get => code2_; set { SetProperty(ref code2_, value); } }

        private Brush ZB1_ = Brushes.Gainsboro;
        public Brush ZB1 { get => ZB1_; set { SetProperty(ref ZB1_, value); } }
        private Brush ZB2_ = Brushes.Gainsboro;
        public Brush ZB2 { get => ZB2_; set { SetProperty(ref ZB2_, value); } }
        public void Uichange(string traano,string cod1, Brush brush1)
        {
            if (cod1=="")
            {
                brush1 = Brushes.Gainsboro;
            }
            if (traano == "1")
            {

                code1 = cod1;
                ZB1 = brush1;
            }
            else
            {
                code2 = cod1;
                ZB2 = brush1;
            }
        }
        public void Uichangecolor(string text, Brush brush1)
        {
            code1 = text;
            code2 = text;
            ZB1 = brush1;
                ZB2 = brush1;
        }
        #region 绑定
        private string textErr;
        /// <summary>
        /// 错误文本
        /// </summary>
        public string TextErr { get => textErr; set { SetProperty(ref textErr, value); } }

        //所有信息
        List<ErrInfo> errInfos = new List<ErrInfo>();
        struct ErrInfo
        {
            public bool IsTemp;//临时
            public string Name;//名称、错误组名
            public string ErrText;//错误信息
        }
        public ICommand ClearTextInfoCommand { get => new DelegateCommand(ClearTextInfo); }
        /// <summary>
        /// 清除信息文本
        /// </summary>
        public void ClearTextInfo()
        {
            TextBoxLog.ClearLog();
        }
        public ICommand ClearTextErrCommand { get => new DelegateCommand(ClearTextErr); }
        /// <summary>
        /// 清除全部错误文本
        /// </summary>
        public void ClearTextErr()
        {
            errInfos.Clear();
            UpdataErrToUi();
            //WarnInfo.RemoveAll(WarnInfoType.AlwayWarn);
        }
        /// <summary>
        /// 添加一个常驻错误
        /// </summary>
        /// <param name="err"></param>
        public void AddTextErr(string err)
        {
            AddTextErr(new string[] { err });
        }

        /// <summary>
        /// 添加一个常驻错误
        /// </summary>
        /// <param name="err"></param>
        public void AddTextErr(string name, string err)
        {
            AddTextErr(name, new string[] { err });
        }

        /// <summary>
        /// 添加一个常驻错误
        /// </summary>
        /// <param name="err"></param>
        public void AddTextErr(IEnumerable<string> errs)
        {
            AddTextErr(string.Empty, errs);
        }

        /// <summary>
        /// 添加一个常驻错误
        /// </summary>
        /// <param name="err"></param>
        public void AddTextErr(string name, IEnumerable<string> errs)
        {
            if (errs == null)
                return;

            foreach (var item in errs)
            {
                ErrInfo errInfo = new ErrInfo();
                errInfo.IsTemp = false;
                errInfo.Name = name;
                errInfo.ErrText = item;
                errInfos.Add(errInfo);
            }

            UpdataErrToUi();
        }

        /// <summary>
        /// 添加临时错误
        /// </summary>
        /// <param name="err"></param>
        public void AddTempTextErr(IEnumerable<string> errs)
        {
            AddTempTextErr(string.Empty, errs);
        }

        /// <summary>
        /// 添加临时错误
        /// </summary>
        /// <param name="err"></param>
        public void AddTempTextErr(string name, IEnumerable<string> errs)
        {
            errInfos.RemoveAll(i => i.Name == name);

            if (errs != null && errs.Any())
                foreach (var item in errs)
                {
                    ErrInfo errInfo = new ErrInfo();
                    errInfo.IsTemp = true;
                    errInfo.Name = name;
                    errInfo.ErrText = item;
                    errInfos.Add(errInfo);
                }

            UpdataErrToUi();
        }
        private void UpdataErrToUi()
        {
            TextErr = string.Join(Environment.NewLine, errInfos?.OrderBy(o => (o.Name, o.IsTemp))?.Select(o => string.IsNullOrEmpty(o.Name) ? o.ErrText : $"[{o.Name}]{o.ErrText}") ?? new string[] { });
        }
        #endregion

        #region 页面加载时任务
        /// <summary>
        /// 页面第一次加载时执行的任务
        /// </summary>
        public void LoadTask()
        {
            for (int i = 0; i < 30; i++)
            {
                ChannelViewModel viewModel = new ChannelViewModel()
                {
                    num = (6-(i/5)).ToString()+"-"+ (5-(i % 5)).ToString(),
                    Mag = (6 - (i / 5)).ToString() + "-" + (5 - (i % 5)).ToString(),
                    Code = "无料",
                };
                panel.Children.Add(new ChannelView(viewModel));
                panelviewModels.Add(viewModel);
            }
            //注册警告事件
            WarnInfo.WarnInfoChanged += (all, add, rem) =>
            {
                //界面展示
                TextErr = string.Join(Environment.NewLine, all.OrderBy(o => (o.WarnType, o.Source, o.Text)));
                //日志记录
                Logs.Write(add.Concat(rem).Select(o => o.ToString()), LogsType.Warning);
                //数据库保存
                if (WarnInfoDb.IsEnabled)
                {
                    WarnInfoDb.db.Insertable(WarnInfoItemDb.GetList(add)).ExecuteCommand();
                    WarnInfoDb.db.Updateable(WarnInfoItemDb.GetList(rem)).ExecuteCommand();
                }
            };

            Task.Run(PlcErrListen);
        }

        /// <summary>
        /// 根据Excel里面的内容监听plc错误信息
        /// </summary>
        async void PlcErrListen()
        {
            //Excel解析的错误格式
            var excelErrAll = ExcelDeviceAlarmModel.GetDatas(LocalFile.PlcDotPath);
            while (true)
            {
                //需要将null替换为设备，如“LocalStatic.Plc”，并去里面解开注释
                var excelErr = ExcelDeviceAlarmModel.ReadPlcAlarm(excelErrAll, LocalFile.Config.Plc);

                WarnInfo.AddOrUpdate(excelErr.Select(o => new WarnInfoItem()
                {
                    Text = o.名称,
                    WarnType = WarnInfoType.WhileWarn,
                    Level = o.级别,
                    Solution = o.解决方式
                }), "PLC");

                await Task.Delay(500);
            }
        }
        #endregion

        #region 业务

        private RunState runState = RunState.Stop;
        /// <summary>
        /// 运行状态
        /// </summary>
        public RunState RunState { get => runState; set { SetProperty(ref runState, value); } }

        public ICommand RunStateClickCommand { get => new DelegateCommand<RunStateButtonClick>(RunStateClick); }
        /// <summary>
        /// 运行状态
        /// </summary>
        public void RunStateClick(RunStateButtonClick clickrunState)
        {
            if (clickrunState == RunStateButtonClick.Start)
            {
                TextBoxLog.AddLog("点击开始");
                Start();
            }
            else if (clickrunState == RunStateButtonClick.Pause)
            {
                TextBoxLog.AddLog("点击暂停");
                Pause();
            }
            else if (clickrunState == RunStateButtonClick.Continue)
            {
                TextBoxLog.AddLog("点击继续");
                Continue();
            }
            else if (clickrunState == RunStateButtonClick.Stop)
            {
                TextBoxLog.AddLog("点击停止");
                Stop();
            }
            else if (clickrunState == RunStateButtonClick.Rset)
            {

            }
        }

        /// <summary>
        /// 开始
        /// </summary>
        private void Start()
        {
            cancellationToken = new CancellationTokenSource();
            manualReset = new ManualResetEvent(true);
            Task.Run(TaskAll);
            RunState = RunState.Run;
        }

        /// <summary>
        /// 暂停
        /// </summary>
        public void Pause()
        {
            manualReset.Reset();
            RunState = RunState.Pause;
        }

        /// <summary>
        /// 继续
        /// </summary>
        public void Continue()
        {
            manualReset.Set();
            RunState = RunState.Run;
        }

        /// <summary>
        /// 停止
        /// </summary>
        public void Stop()
        {
            cancellationToken.Cancel();
            RunState = RunState.Stop;
        }

        private void TaskAll()
        {

            try
            {
                OutputStatChartView.viewModel.UpdataDataNew();
                ClearModel();

                List<HTZD_Assemble> list = GETVisioninfo1();
                if (list == null)
                {
                    TextBoxLog.AddLog($"数据库获取tray盘中的产品信息错误");
                    return;
                }
                if (list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        panelviewModels[29 - i].adddata(list[i].barCode, list[i].WriteCodeResult);
                        TextBoxLog.AddLog($"tray盘位置{panelviewModels[29 - i].num}，编码{panelviewModels[29 - i].SQLSN}，状态{panelviewModels[29 - i].okng}");
                    }
                }
                string reyul = getpanl();
                if (reyul!="OK")
                {
                    TextBoxLog.AddLog(reyul);
                    return;
                }
                Task.WaitAll(Task1(), Task2());
            }
            catch (Exception ex)
            {
                TextBoxLog.AddLog($"错误：{ex.ToString()}");
            }
            finally
            {
                Stop();
                TextBoxLog.AddLog("已停止：全部");
            }
        }
        public string getpanl()
        {
            try
            {
                string code1 = "";
                string code2 = "";
                int cod1 = 0;
                int cod2 = 0;
                List<HTZD_Assemble> list1 = GetdtartInfo();
                if (list1 == null)
                {
                    Uichangecolor("数据库获取本轮到料的产品信息错误", Brushes.Crimson);
                    return "数据库获取本轮到料的产品信息错误";
                }
                if (list1.Count != 0 && list1.Count != 15 && list1.Count != 30)
                {
                    Uichangecolor($"数据库获取本轮到料的产品信息错误,数量为{list1.Count},{list1.ToString()}", Brushes.Crimson);
                    return $"数据库获取本轮到料的产品信息错误,数量为{list1.Count},{list1.ToString()}";
                }
                if (list1.Count > 0)
                {
                    for (int i = list1.Count-1;i >=0; i--)
                    {
                        if (list1[i].WriteCodeTrackNo == "1")
                        {
                            cod1 = cod1 + 1;
                            code1 = code1 + $"{cod1}.{list1[i].barCode}进程{list1[i].PlatingStatus}"+ "\r\n";
                        }
                        else
                        {
                            cod2 = cod2 + 1;
                            code2 = code2 + $"{cod2}.{list1[i].barCode}进程{list1[i].PlatingStatus}" + "\r\n";
                        }
                    }
                    if ((cod2!=0&&cod2!=15) ||(cod1 != 0 && cod1 != 15))
                    {
                        if (cod1 != 0 && cod1 != 15)
                        {
                            Uichange("1",code1, Brushes.Crimson);
                        }
                        else
                        {
                            Uichange("1", code1, Brushes.ForestGreen);
                        }
                        if (cod2 != 0 && cod2 != 15)
                        {
                            Uichange("2", code2, Brushes.Crimson);
                        }
                        else
                        {
                            Uichange("2", code2, Brushes.ForestGreen);
                        }
                        return $"1号皮带到料{cod1}个，2号皮带到料{cod2}个数量异常";
                    }
                }
                Uichange("1", code1, Brushes.ForestGreen);
                Uichange("2", code2, Brushes.ForestGreen);
                return "OK";
            }
            catch (Exception ee )
            {
                Uichangecolor(ee.Message, Brushes.Crimson);
                return ee.Message;
            }

        }
        
        /// sqlite 保持2个tray盘的临时数据，到位后如果没有供料状态的则在本站数据库读取接下来的30。然后用sqlite判断是否正确，是前15还是后15，是否连续（状态待供料-》供料）
        ///  供料处理完确认sqlite的没有供料状态的
        ///  视觉确认完成后删除sqlite的在tray盘的数据
        ///  抓取到tray盘时写入本站数据库
        /// </summary>
        /// <returns></returns>
        private async Task Task1()
        {
            try
            {
                while (true) {
                    await Task.Delay(500);
                    //监听：开始、暂停、停止
                    While.Wait(cancellationToken.Token, manualReset);
                    Solve();
                    While.Wait(cancellationToken.Token, manualReset);
                    confirmationgrab();
                    While.Wait(cancellationToken.Token, manualReset);
                    Requestgrab();
                    While.Wait(cancellationToken.Token, manualReset);
                    Arrive();
                }
            }
            catch (OperationCanceledException)
            {
                TextBoxLog.AddLog("供料已停止");
            }
            catch (Exception ex)
            {
                TextBoxLog.AddLog($"错误：{ex.ToString()}");
            }
            finally
            {
                cancellationToken?.Cancel();
            }
        }
        /// <summary>
        /// 到料确认（sqlite 保持1个tray盘的临时数据）抓取后状态由供料改为抓取并写入下料站数据库，供料完成确认后删除，
        /// 到料信号后从全线该皮带抓取15个，判断这15个最小的是否
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void Arrive()
        {
            //int vum = 0;
            var plcinfo = LocalStatic.Plc.Read<bool>("轨道1物料到位");
            if (plcinfo.IsSucceed == true && plcinfo.Value == true)
            {
                var plcinfo1=LocalStatic.Plc.Read<int>("PC轨道1到位序号");
                if (plcinfo1.IsSucceed == true && plcinfo1.Value == 0)
                {
                    if (LocalFile.Config.Mlpd)
                    {
                        //mlprepare1("1");
                        string result = MESModels.MLGetInfo("1");
                        if (result != "OK")
                        {
                            TextBoxLog.AddLog(result);
                            TextBoxLog.AddLog("PLC通信：PC轨道1到位序号:3");
                            LocalStatic.Plc.Write("PC轨道1到位序号", 3);
                            Stop();
                            return;
                        }

                        TextBoxLog.AddLog("PLC通信：PC轨道1到位序号:1");
                        LocalStatic.Plc.Write("PC轨道1到位序号",1);

                        TextBoxLog.AddLog("模拟轨道1物料到位");
                    }
                    else
                    {
                        //prepare1("1");
                        string result = MESModels.GetInfo(LocalFile.Config.ischeck);
                        if (result != "OK")
                        {
                            TextBoxLog.AddLog($"轨道1物料到位失败：{result}");
                            TextBoxLog.AddLog("PLC通信：PC轨道1到位序号:3");
                            LocalStatic.Plc.Write("PC轨道1到位序号", 3);
                            Stop();
                            return;
                        }
                        result = MESModels.UpdatafsInfo("1");
                        string[] rdd = result.Split(':');
                        if (rdd[0] != "成功")
                        {
                            TextBoxLog.AddLog($"轨道1物料到位失败：{result}");
                            TextBoxLog.AddLog("PLC通信：PC轨道1到位序号:3");
                            LocalStatic.Plc.Write("PC轨道1到位序号", 3);
                            Stop();
                            return;
                        }
                        else
                        {
                            TextBoxLog.AddLog($"PLC通信：PC轨道1到位序号:{rdd[1]}");
                            LocalStatic.Plc.Write("PC轨道1到位序号", rdd[1]);
                            TextBoxLog.AddLog("轨道1物料到位" + rdd[1] + rdd[2]);
                        }

                    }
                    string reyul = getpanl();
                    if (reyul != "OK")
                    {
                        TextBoxLog.AddLog(reyul);
                        Stop();
                        return;
                    }
                }
            }
            plcinfo = LocalStatic.Plc.Read<bool>("轨道2物料到位");
            if (plcinfo.IsSucceed == true && plcinfo.Value == true)
            {
                var plcinfo1 = LocalStatic.Plc.Read<int>("PC轨道2到位序号");
                if (plcinfo1.IsSucceed == true && plcinfo1.Value == 0)
                {
                    if (LocalFile.Config.Mlpd)
                    {
                        //mlprepare1("1");
                        string result = MESModels.MLGetInfo("2");
                        if (result != "OK")
                        {
                            TextBoxLog.AddLog(result);
                            TextBoxLog.AddLog($"PLC通信：PC轨道2到位序号:3");
                            LocalStatic.Plc.Write("PC轨道2到位序号", 3);
                            Stop();
                            return;
                        }

                        TextBoxLog.AddLog($"PLC通信：PC轨道2到位序号:2");
                        LocalStatic.Plc.Write("PC轨道2到位序号",2);

                        TextBoxLog.AddLog("模拟轨道2物料到位");
                    }
                    else
                    {
                        //prepare1("1");
                        string result = MESModels.GetInfo(LocalFile.Config.ischeck);
                        if (result != "OK")
                        {
                            TextBoxLog.AddLog($"轨道2物料到位失败：{result}");
                            TextBoxLog.AddLog($"PLC通信：PC轨道2到位序号:3");
                            LocalStatic.Plc.Write("PC轨道2到位序号", 3);
                            Stop();
                            return;
                        }
                        result = MESModels.UpdatafsInfo("2");
                        string[] rdd = result.Split(':');
                        if (rdd[0] != "成功")
                        {
                            TextBoxLog.AddLog($"轨道2物料到位失败：{result}");
                            TextBoxLog.AddLog($"PLC通信：PC轨道2到位序号:3");
                            LocalStatic.Plc.Write("PC轨道2到位序号", 3);
                            Stop();
                            return;
                        }
                        else
                        {
                            TextBoxLog.AddLog($"PLC通信：PC轨道2到位序号:{rdd[1]}");
                            LocalStatic.Plc.Write("PC轨道2到位序号", rdd[1]);
                            TextBoxLog.AddLog("轨道2物料到位" + rdd[1] + rdd[2]);
                        }

                    }
                    string reyul = getpanl();
                    if (reyul != "OK")
                    {
                        TextBoxLog.AddLog(reyul);
                        Stop();
                        return;
                    }
                }
            }
        }
        ///// <summary>
        ///// 1号皮带全线是否有待供料的，如果没有则将最小的30个改为供料
        ///// </summary>
        ///// <returns></returns>
        ///// <exception cref="NotImplementedException"></exception>
        //private void mlprepare1(string TrackNo)
        //{
        //    string result = MESModels.MLGetInfo(TrackNo);
        //    if (result != "OK")
        //    {
        //        TextBoxLog.AddLog(result);
        //        LocalStatic.Plc.Write("PC轨道1到位序号", 3);
        //        Stop();
        //        return;
        //    }

        //    LocalStatic.Plc.Write("PC轨道1到位序号", 1);

        //    TextBoxLog.AddLog("模拟轨道1物料到位");
        //    return;

        //}
        
        ///// <summary>
        ///// 2号皮带全线是否有待供料的，如果没有则将最小的30个改为供料
        ///// </summary>
        ///// <returns></returns>
        ///// <exception cref="NotImplementedException"></exception>
        //private void mlprepare2(string TrackNo)
        //{
        //    string result = MESModels.MLGetInfo(TrackNo);
        //    if (result != "OK")
        //    {
        //        TextBoxLog.AddLog(result);
        //        LocalStatic.Plc.Write("PC轨道2到位序号", 3);
        //        Stop();
        //        return;
        //    }
        //    LocalStatic.Plc.Write("PC轨道2到位序号", 2);
        //    TextBoxLog.AddLog("模拟轨道2物料到位");
        //    return;

        //}
        ///// <summary>
        ///// 1号皮带全线是否有待供料的，如果没有则将最小的30个改为供料
        ///// </summary>
        ///// <returns></returns>
        ///// <exception cref="NotImplementedException"></exception>
        //private void prepare1(string TrackNo)
        //{

        //    string result = MESModels.GetInfo(LocalFile.Config.ischeck);
        //    if (result != "OK")
        //    {
        //        TextBoxLog.AddLog($"轨道1物料到位失败：{result}");
        //        LocalStatic.Plc.Write("PC轨道1到位序号", 3);
        //        Stop();
        //        return;
        //    }
        //    result = MESModels.UpdatafsInfo(TrackNo);
        //    string[] rdd = result.Split(':');
        //    if (rdd[0] != "成功")
        //    {
        //        TextBoxLog.AddLog($"轨道1物料到位失败：{result}");
        //        LocalStatic.Plc.Write("PC轨道1到位序号", 3);
        //        Stop();
        //        return;
        //    }
        //    else
        //    {
        //        LocalStatic.Plc.Write("PC轨道1到位序号", rdd[1]);
        //        TextBoxLog.AddLog("轨道1物料到位" + rdd[1] + rdd[2]);
        //        return;
        //    }

        //}
        ///// <summary>
        ///// 2号皮带全线是否有待供料的，如果没有则将最小的30个改为供料
        ///// </summary>
        ///// <returns></returns>
        ///// <exception cref="NotImplementedException"></exception>
        //private void prepare2(string TrackNo)
        //{
        //    string result = MESModels.GetInfo(LocalFile.Config.ischeck);
        //    if (result != "OK")
        //    {
        //        TextBoxLog.AddLog(result);
        //        LocalStatic.Plc.Write("PC轨道2到位序号", 3);
        //        Stop();
        //        return;
        //    }
        //    result = MESModels.UpdatafsInfo(TrackNo);
        //    string[] rdd = result.Split(':');
        //    if (rdd[0] != "成功")
        //    {
        //        TextBoxLog.AddLog(result);
        //        LocalStatic.Plc.Write("PC轨道2到位序号", 3);
        //        Stop();
        //        return;
        //    }
        //    else
        //    {
        //        LocalStatic.Plc.Write("PC轨道2到位序号", rdd[1]);
        //        TextBoxLog.AddLog("轨道2物料到位"+ rdd[1]+ rdd[2]);
        //        return;
        //    }
        //}
        /// <summary>
        /// 抓取确认
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void confirmationgrab()
        {
            var data = LocalStatic.Plc.Read<bool>("向PC发物料放置到旋转台");
            if (data.IsSucceed && data.Value)
            { 
                var data1 = LocalStatic.Plc.Read<bool>("收到PC放置确认");
                if (data1.IsSucceed && !data1.Value)
                {
                    string result="";
                    if (LocalFile.Config.Mlpd)
                    {
                        result = MESModels.mlupdatamoveinfo(LocalFile.Config.ischeck);
                    }
                    else
                    {
                        result = MESModels.updatamoveinfo(LocalFile.Config.ischeck);

                    }
                    //string result = MESModels.updatamoveinfo(LocalFile.Config.ischeck);
                    //string[] msg = result.Split(':');
                    if (result == "成功")
                    {
                        TextBoxLog.AddLog($"PLC通信：收到PC放置确认:true");
                        LocalStatic.Plc.Write("收到PC放置确认", true);
                        TextBoxLog.AddLog("物料放置到旋转台");
                    }
                    else
                    {
                        TextBoxLog.AddLog($"物料放置到旋转台确认失败:{result}");
                        Stop();
                        return;
                    }
                }
            }
        }
        

        /// <summary>
        /// 抓取请求
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void Requestgrab()
        {
            var data = LocalStatic.Plc.Read<bool>("向PC请求抓取"); 
            if (data.IsSucceed && data.Value)
            {
                var data2 = LocalStatic.Plc.Read<Int32>("入料搬运夹爪数据");
                if (data2.IsSucceed && data2.Value == 0)
                {
                    var data1 = LocalStatic.Plc.Read<Int32>("搬运抓取次数");
                    if (data1.IsSucceed)
                    {
                        string result = MESModels.getmoveinfo(data1.Value);
                        string[] msg = result.Split(':');
                        if (msg[0] == "成功")
                        {
                            TextBoxLog.AddLog($"PLC通信：入料搬运夹爪数据:{msg[1]}");
                            LocalStatic.Plc.Write("入料搬运夹爪数据", msg[1]);
                            TextBoxLog.AddLog($"抓取第{data1.Value+1}组搬运夹爪状态{msg[2]}");
                        }
                        else
                        {
                            TextBoxLog.AddLog($"抓取第{data1.Value + 1}组搬运夹爪失败{result}");
                            //TextBoxLog.AddLog(result);
                            Stop();
                            return;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 供料的30个处理完了
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void Solve()
        {
            var data = LocalStatic.Plc.Read<bool>("PC查询数据抓完");
            if (data.IsSucceed && data.Value)
            {
                var data1 = LocalStatic.Plc.Read<bool>("PC查询OK");
                if (data1.IsSucceed && !data1.Value)
                {
                    string result = MESModels.confirmmoveinfo();
                    if (result == "成功")
                    {
                        string reyul = getpanl();
                        if (reyul != "OK")
                        {
                            TextBoxLog.AddLog(reyul);
                            Stop();
                            return;
                        }
                        TextBoxLog.AddLog($"PLC通信：PC查询OK:true");
                        LocalStatic.Plc.Write("PC查询OK", true);
                        TextBoxLog.AddLog($"供料抓完确认完成");
                        //reyul = getpanl();
                        //if (reyul!="OK")
                        //{
                        //    TextBoxLog.AddLog(reyul);
                        //    Stop();
                        //    return;
                        //}
                    }
                    else
                    {
                        TextBoxLog.AddLog($"供料抓完确认失败：{result}");
                        //TextBoxLog.AddLog(result);
                        Stop();
                    }
                }
            }
        }
        /// <summary>
        /// 下料请求将本站数据库中的待下料改为下料
        /// 入堆将tray盘中改为待下料
        /// 拍照确认将入tray盘改为tray中
        /// 抓取到tray盘将产品信息写入本站数据库并将状态改为入tray盘
        /// </summary>
        /// <returns></returns>
        private async Task Task2()
        {
            try
            {
                while (true)
                {
                    await Task.Delay(500);
                    //监听：开始、暂停、停止
                    While.Wait(cancellationToken.Token, manualReset);
                    Baiting();
                    While.Wait(cancellationToken.Token, manualReset);
                    ToBaiting();
                    While.Wait(cancellationToken.Token, manualReset);
                    Vision();
                    While.Wait(cancellationToken.Token, manualReset);
                    Totray();
                    While.Wait(cancellationToken.Token, manualReset);
                }
            }
            catch (OperationCanceledException)
            {
                TextBoxLog.AddLog("已停止tray盘搬运");
            }
            catch (Exception ex)
            {
                TextBoxLog.AddLog($"错误：{ex.ToString()}");
            }
            finally
            {
                cancellationToken?.Cancel();
            }
        }
        /// <summary>
        /// 机器人将产品放入tray盘
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void Totray()
        {
            var data = LocalStatic.Plc.Read<bool>("向PC发模块放入萃盘");
            if (data.IsSucceed && data.Value)
            {
                var data1 = LocalStatic.Plc.Read<bool>("PC收到模块放入萃盘");
                if (data1.IsSucceed && !data1.Value)
                {
                    string result = MESModels.trayinfo();
                    string[] msg = result.Split(':');
                    if (msg[0] == "成功")
                    {
                        string[] sn1 = msg[1].Replace("\r\n","").Split(' ');
                        int A101StudentCount = panelviewModels.Count(t => t.Code == "就绪");
                        for(int i= 0; i<5;i++)
                        {
                            string[] sn = sn1[i].Split(',');
                            panelviewModels[29-A101StudentCount - i].adddata(sn[0], sn[1]);
                        }
                        TextBoxLog.AddLog($"PLC通信：PC收到模块放入萃盘:true");
                        LocalStatic.Plc.Write("PC收到模块放入萃盘", true);

                        TextBoxLog.AddLog($"放入萃盘成功{msg[1]}");
                    }
                    else
                    {
                        TextBoxLog.AddLog($"放入萃盘失败{result}");
                        //TextBoxLog.AddLog(result);
                        Stop();
                    }
                }
            }
        }

        /// <summary>
        /// 照相确认
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void Vision()
        {

            var data = LocalStatic.Plc.Read<bool>("触发视觉");
            if (data.IsSucceed && data.Value)
            {
                var data1 = LocalStatic.Plc.Read<bool>("视觉拍照完成");
                if (data1.IsSucceed && !data1.Value)
                {
                    string vision = LocalStatic.Vision.SendMes("code");
                    string[] visiong = vision.Trim().Split(';');
                    if (visiong.Length!=30)
                    {
                        TextBoxLog.AddLog($"视觉确认失败,视觉数量获取错误，有{visiong.Length}条：{vision}");
                        Stop();
                        return;
                    }
                    string result = "";
                    List<HTZD_Assemble>  list = GETVisioninfo1();
                    if (list==null)
                    {
                        TextBoxLog.AddLog($"视觉确认失败,数据库查询错误");
                        Stop();
                        return;
                    }
                    if (list.Count!=30)
                    {
                        TextBoxLog.AddLog($"视觉确认失败,数据库数量获取错误，有{list.Count}条：{list.ToString()}");
                        Stop();
                        return;
                    }
                    for (int i=0;i<30;i++)
                    {
                        panelviewModels[29-i].check(list[i].barCode, list[i].WriteCodeResult, visiong[i], LocalFile.Config.Mlpd);
                        list[i].PlatingStatus="tray盘确认";
                        TextBoxLog.AddLog(panelviewModels[29-i].Mag);
                    }
                    int A101StudentCount = panelviewModels.Count(t => t.Code == "OK" || t.Code == "空");
                    if (A101StudentCount==30)
                    {
                        string rel = UpdateVisioninfo1(list);
                        if (rel != "OK")
                        {
                            TextBoxLog.AddLog(rel);
                            Stop();
                            return;
                        }
                        else
                        {
                            TextBoxLog.AddLog($"PLC通信：视觉拍照完成:true");
                            LocalStatic.Plc.Write("视觉拍照完成", true);
                            TextBoxLog.AddLog($"视觉确认完成");
                        }
                    }
                    else
                    {
                        TextBoxLog.AddLog($"视觉确认失败：视觉确认{A101StudentCount}个，未全部完成");
                        Stop();
                        return;
                    }
                    //if (LocalFile.Config.Mlpd)
                    //{
                    //    result = MESModels.MLVisioninfo(visiong);
                    //}
                    //else
                    //{

                    //    result = MESModels.Visioninfo(visiong);
                    //}
                    //string[] msg = result.Split(':');
                    //if (msg[0] == "成功")
                    //{
                    //    LocalStatic.Plc.Write("视觉拍照完成", true);
                    //    TextBoxLog.AddLog($"视觉拍照完成{msg[1]}");
                    //}
                    //else
                    //{
                    //    TextBoxLog.AddLog($"视觉报错{msg[1]}");
                    //    Stop();
                    //}

                }
            }
        }

        /// <summary>
        /// tray盘入堆
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void ToBaiting()
        {
            var data = LocalStatic.Plc.Read<bool>("向PC发出堆料请求");
            if (data.IsSucceed && data.Value)
            {
                var data1 = LocalStatic.Plc.Read<bool>("PC允许堆料");
                if (data1.IsSucceed && !data1.Value)
                {
                    string result = MESModels.pileinfo(LocalFile.Config.Mlpd);
                    string[] msg = result.Split(':');
                    if (msg[0] == "成功")
                    {
                        TextBoxLog.AddLog($"PLC通信：PC允许堆料:true");
                        LocalStatic.Plc.Write("PC允许堆料", true);
                        TextBoxLog.AddLog($"允许堆料：{msg[1]}");
                        ClearModel();
                    }
                    else
                    {
                        TextBoxLog.AddLog($"禁止堆料{msg[1]}");
                        Stop();
                        return;
                    }

                    OutputStatChartView.viewModel.UpdataDataNew();
                }
            }
        }/// <summary>
        /// 将tray盘在页面上的信息清空
        /// </summary>
        private void ClearModel()
        {

            for (int i = 0; i < 30; i++)
            {
                panelviewModels[i].SQLSN = "";
                panelviewModels[i].VisionSN = "";
                panelviewModels[i].mag = "";
                panelviewModels[i].okng = "";
                panelviewModels[i].Mag = (6 - (i / 5)).ToString() + "-" + (5 - (i % 5)).ToString();
                panelviewModels[i].Code = "无料";
            }
        }
        /// <summary>
        /// 下料请求
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void Baiting()
        {
            var data = LocalStatic.Plc.Read<bool>("向PC发出整堆出料");
            if (data.IsSucceed && data.Value)
            {
                var data1 = LocalStatic.Plc.Read<bool>("PC允许整堆出料");
                if (data1.IsSucceed && !data1.Value)
                {
                    string result = MESModels.confirmbaitinginfo();
                    if (result == "成功")
                    {
                        TextBoxLog.AddLog($"PLC通信：PC允许整堆出料:true");
                        LocalStatic.Plc.Write("PC允许整堆出料", true);
                        TextBoxLog.AddLog("允许整堆下料");
                    }
                    else
                    {
                        TextBoxLog.AddLog($"禁止整堆下料{result}");
                        //TextBoxLog.AddLog(result);
                        Stop();
                        return;
                    }
                }
            }
        }
        #endregion
    }
}
